<template>
  <div class="organize-tree">
    <el-input
      placeholder="请输入搜索内容"
      prefix-icon="Search"
      maxlength="100"
      clearable
      v-model="filterText"
    ></el-input>
    <div class="tree-box" ref="TreeBoxRef" v-loading="loading">
      <el-tree
        ref="OrganizeTreeRef"
        node-key="id"
        :data="treeData"
        :default-expanded-keys="defaultExpandedKeys"
        :expand-on-click-node="false"
        :filter-node-method="filterNode"
        :props="{ class: customNodeClass, label: 'name', children: 'childs' }"
        @node-click="handleNodeClick"
        @node-expand="nodeExpand"
        @node-collapse="nodeCollapse"
      >
        <template #default="{ data }">
          <span :id="getId(data)">{{ data.name }}</span>
        </template>
      </el-tree>
    </div>
  </div>
</template>

<script setup>
import { userGroupAll, companyGroupAll, platformGroupAll } from '@/api/system';

const props = defineProps({
  activeOranize: {
    type: Object,
    default: () => {}
  },
  roleType: {
    type: String,
    default: '' // 1团队 2公司 3平台
  }
});
const emit = defineEmits();

const nowTime = Date.now();
function getId(data) {
  return nowTime + '-' + data.id;
}

const filterText = ref('');
const loading = ref(false);
const treeData = ref([]);
const defaultExpandedKeys = reactive([]);

const getData = () => {
  const api = {
    1: userGroupAll,
    2: companyGroupAll,
    3: platformGroupAll
  }[props.roleType];
  loading.value = true;
  api()
    .then(res => {
      const resData = res.data || [];
      deepTree(resData);
      if (props.roleType == 3) {
        treeData.value = [
          {
            id: undefined,
            name: '全部',
            childs: resData || []
          }
        ];
      } else {
        treeData.value = resData || [];
      }

      if (!defaultExpandedKeys.length) {
        getExpandedKeys(treeData.value, 1);
      }

      const thisOrganize = hasThisOrganize(treeData.value);
      if (props.activeOranize?.id && thisOrganize) {
        handleNodeClick(thisOrganize);
      } else {
        handleNodeClick(treeData.value[0]);
      }
      nextTick(() => {
        search();
      });
    })
    .finally(() => {
      loading.value = false;
    });
};

// 获取默认展开的key
function getExpandedKeys(list, level) {
  list.forEach(item => {
    defaultExpandedKeys.push(item.id);
    if (item.childs?.length && level < 2) {
      getExpandedKeys(item.childs, level + 1);
    }
  });
}

// 节点被展开
function nodeExpand(data) {
  defaultExpandedKeys.push(data.id);
}

// 节点被关闭
function nodeCollapse(data) {
  defaultExpandedKeys.splice(
    defaultExpandedKeys.findIndex(item => item === data.id),
    1
  );
}

function deepTree(list, parent) {
  parent = parent || {};
  list.forEach(item => {
    const parentNamePath = parent.name_path || [];
    item.name_path = [...parentNamePath, item.name];
    if (item.childs?.length) deepTree(item.childs, item);
  });
}

function hasThisOrganize(list) {
  if (!props.activeOranize?.id) return '';
  for (let i = 0; i < list.length; i++) {
    const item = list[i];
    if (item.id === props.activeOranize?.id) return item;
    if (item.childs?.length) {
      const thisOrganize = hasThisOrganize(item.childs);
      if (thisOrganize) return thisOrganize;
    }
  }
}

function search() {
  OrganizeTreeRef.value?.filter(filterText.value);
}
const OrganizeTreeRef = ref();
watch(filterText, () => {
  search();
});

const filterNode = (value, data) => {
  if (!value) return true;
  return data.name.includes(value);
};

const TreeBoxRef = ref();
const handleNodeClick = (data, node) => {
  if (node && (!data || data.id === props.activeOranize?.id)) return;
  emit('activeChange', data || {});
  if (filterText.value) {
    filterText.value = '';
    nextTick(() => {
      const boxDom = TreeBoxRef.value;
      const itemDom = document.getElementById(getId(data || {}));
      if (!boxDom || !itemDom) return;
      boxDom.scrollTop = itemDom.offsetTop;
    });
  }
};

const customNodeClass = data => {
  if (data.id === props.activeOranize?.id) {
    return 'is-active-organize';
  }
  return null;
};

defineExpose({ getData });
</script>

<style lang="scss" scoped>
.organize-tree {
  min-width: 285px;
  max-width: 285px;
  padding: 10px 12px;
  padding-right: 0;
  display: flex;
  flex-direction: column;
  height: calc(100vh - 50px);
  :deep(.el-tree) {
    width: max-content;
    min-width: 100%;
    .el-tree-node__expand-icon {
      content: url('@/assets/images/open.png');
      margin-top: 1px;
      width: 12px;
      height: 12px;
      &.expanded {
        content: url('@/assets/images/closed.png');
        transform: none;
      }
      svg {
        display: none;
      }
    }
    .is-active-organize > .el-tree-node__content {
      color: var(--el-color-primary);
      background-color: var(--el-color-primary-light-8);
    }
  }
}
.tree-box {
  flex: 1;
  margin-top: 10px;
  border-radius: 4px;
  padding: 10px 12px;
  overflow: auto;
  background-color: #fff;
  box-shadow: 0 0 12px #0000000d;
}
</style>
